package com.tticar.invmanager.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.tticar.invmanager.common.utils.DateUtils;
import com.tticar.invmanager.entity.WStore;
import com.tticar.invmanager.service.*;
import com.tticar.invmanager.tticar.service.IGoodsOrderService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 首页
 * </p>
 *
 * @author jiwenbin
 * @since 2018-09-05
 */
@Controller
@RequestMapping("/home")
public class HomeController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    IRepositoryCountService repositoryCountService;
    @Autowired
    IOutRepositoryDetailService outRepositoryDetailService;
    @Autowired
    IPPurchaseService purchaseService;
    @Autowired
    IMSalesService salesService;
    @Autowired
    IWStoreService storeService;
    @Autowired
    private IGoodsOrderService goodsOrderService;

    @GetMapping
    public String home(ModelMap modelMap) {

        modelMap.put("repositoryCount", getRepositoryCount()); // 库存总数量，库存总金额
        modelMap.put("amountCount", getAmountCount()); // 待付款总金额,待收款总金额
        modelMap.put("todaySellCount", getTodaySellCount()); // 今日线下销售总单量,今日线下销售总金额
        modelMap.put("monthSellCount", getMonthSellCount()); // 本月线下销售总单量,本月线下销售总金额
        modelMap.put("todayTticarSellCount", getTodayTticarSellCount()); // 今日平台销售总单量,今日平台销售总金额
        modelMap.put("monthTticarSellCount", getMonthTticarSellCount()); // 本月平台销售总单量,本月平台销售总金额

        return "home";
    }

    /**
     * 库存统计
     * @return
     */
    @GetMapping("repositoryCount")
    @ResponseBody
    public Map getRepositoryCount() {
        Map map = new HashMap<>();
        try {
            Wrapper w1 = new EntityWrapper<>();
            w1.setSqlSelect("sum(count) totalCount");
            Map result1 = repositoryCountService.selectMap(w1);
            map.put("0", (result1 == null || result1.get("totalCount") == null) ? 0 : result1.get("totalCount")); // 库存总数量

            Wrapper w2 = new EntityWrapper<>();
            w2.ne("status", -1);
            w2.ge("order_time",DateUtils.getInstance().getCurrentDayStartTime());
            w2.le("order_time",DateUtils.getInstance().getCurrentDayEndTime());
            w2.setSqlSelect("sum(count) totalCount");
            Map result2 = outRepositoryDetailService.selectMap(w2);
            map.put("1", (result2 == null || result2.get("totalCount") == null) ? 0 : result2.get("totalCount")); // 今日出库量
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return map;
    }

    /**
     * 待付/待收金额统计
     * @return
     */
    @GetMapping("amountCount")
    @ResponseBody
    public Map getAmountCount() {
        Map map = new HashMap<>();
        try {
            Wrapper w1 = new EntityWrapper<>();
            w1.eq("status", 0);
            w1.eq("pay_status", 0);
            w1.setSqlSelect("sum(amount_ing) payableAmount");
            Map result1 = purchaseService.selectMap(w1);

            Wrapper w2 = new EntityWrapper<>();
            w2.eq("status", 0);
            w2.eq("pay_status", 0);
            w2.setSqlSelect("sum(paying_fee) receivableAmount");
            Map result2 = salesService.selectMap(w2);

            map.put("0", (result1 == null || result1.get("payableAmount") == null) ? 0 : result1.get("payableAmount")); // 待付总金额
            map.put("1", (result2 == null || result2.get("receivableAmount") == null) ? 0 : result2.get("receivableAmount")); // 待收总金额
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return map;
    }

    /**
     * 今日线下销售统计
     * @return
     */
    @GetMapping("todaySellCount")
    @ResponseBody
    public Map getTodaySellCount() {
        DateUtils dateUtils = DateUtils.getInstance();
        return getSellCount(dateUtils.getCurrentDayStartTime(), dateUtils.getCurrentDayEndTime());
    }

    /**
     * 本月线下销售统计
     * @return
     */
    @GetMapping("monthSellCount")
    @ResponseBody
    public Map getMonthSellCount() {
        DateUtils dateUtils = DateUtils.getInstance();
        return getSellCount(dateUtils.getCurrentMonthStartTime(), dateUtils.getCurrentMonthEndTime());
    }

    /**
     * 今日平台销售统计
     * @return
     */
    @GetMapping("todayTticarSellCount")
    @ResponseBody
    public Map getTodayTticarSellCount() {
        DateUtils dateUtils = DateUtils.getInstance();
        return getTticarSellCount(dateUtils.getCurrentDayStartTime(), dateUtils.getCurrentDayEndTime());
    }

    /**
     * 本月平台销售统计
     * @return
     */
    @GetMapping("monthTticarSellCount")
    @ResponseBody
    public Map getMonthTticarSellCount() {
        DateUtils dateUtils = DateUtils.getInstance();
        return getTticarSellCount(dateUtils.getCurrentMonthStartTime(), dateUtils.getCurrentMonthEndTime());
    }

    private Map getTticarSellCount(Date startTime, Date endTime) {
        Map map = new HashMap<>();
        try {
            // 1,先查询当前租户的店铺，得到关联的天天爱车店铺id
            Wrapper w = new EntityWrapper<>();
            w.eq("status", 0);
            w.setSqlSelect(WStore.TTSTORE_ID);
            List<Object> TTStoreIdList = storeService.selectObjs(w);
            if (CollectionUtils.isEmpty(TTStoreIdList)) {
                map.put("0", 0);
                map.put("1", 0);
                return map;
            }

            // 2,,再根据天天爱车店铺id获得天天爱车订单
            Wrapper w1 = new EntityWrapper<>();
            w1.eq("isDel", 0);
            w1.ne("status", 77); // 排除取消的订单
            w1.in("storeId", TTStoreIdList);
            w.ge("order_time",startTime);
            w.le("order_time",endTime);
            w1.setSqlSelect("count(1) totalCount,sum(totalMoney) totalAmount");
            Map result = goodsOrderService.selectMap(w1);

            map.put("0", (result == null || result.get("totalAmount") == null) ? 0 : result.get("totalAmount")); // 今日平台销售总金额
            map.put("1", (result == null || result.get("totalCount") == null) ? 0 : result.get("totalCount")); // 今日平台销售总单量
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return map;
    }

    private Map getSellCount(Date startTime, Date endTime) {
        Map map = new HashMap<>();
        try {
            Wrapper w = new EntityWrapper<>();
            w.eq("status", 0);
            w.ge("order_time",startTime);
            w.le("order_time",endTime);
            w.setSqlSelect("count(1) totalCount,sum(goods_fee) totalAmount");
            Map result = salesService.selectMap(w);

            map.put("0", (result == null || result.get("totalAmount") == null ) ? 0 : result.get("totalAmount")); // 线下销售总金额
            map.put("1", (result == null || result.get("totalCount") == null) ? 0 : result.get("totalCount")); // 线下销售总单量
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return map;
    }

}
